package Midium;


import java.util.*;
import java.util.concurrent.BlockingQueue;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

// 二叉树的层序遍历II
// 这么做会超时，因为null太冗余了
//public class Solution107 {
//    public List<List<Integer>> levelOrderBottom(TreeNode root) {
//        List<List<Integer>> allList = new ArrayList<>();
//        Queue<TreeNode> queue = new LinkedList<>();
//        queue.offer(root);
//        int height = 1;
//        while (!queue.isEmpty()) {
//            List<Integer> newList = new ArrayList<>();
//            for (int i = 0; i < height; i++) {
//                if (queue.peek() == null) {
//                    queue.poll();
//                    queue.offer(null);
//                    queue.offer(null);
//                } else {
//                    TreeNode node = queue.poll();
//                    newList.add(node.val);
//                    queue.offer(node.left);
//                    queue.offer(node.right);
//                }
//            }
//            //这时newList可能为空，空的话是不放入的
//            if (!newList.isEmpty()) {
//                allList.add(0, newList);
//                height *= 2;
//            }else
//                break;
//        }
//        return allList;
//    }
//}

//改进：每层的size正好为当前queue的size
public class Solution107 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        List<List<Integer>> allList = new ArrayList<>();
        if (root == null) return allList;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> newList = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size ; i++) {
                TreeNode node = queue.poll();
                newList.add(node.val);
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);

            }
            allList.add(0, newList);
        }
        return allList;
    }
}